package com.ihr360.expr.function.excel;


import com.ihr360.expr.ExprDouble;
import com.ihr360.expr.ExprError;
import com.ihr360.expr.ExprException;
import com.ihr360.expr.context.IEvaluationContext;
import com.ihr360.expr.core.AbstractFunction;
import com.ihr360.expr.core.Expr;
import com.ihr360.expr.utils.Maths;

public class FLOOR extends AbstractFunction
{
    @Override
    public Expr evaluate(IEvaluationContext context, Expr[] args)
            throws ExprException {
        assertArgCount(args, 2);
        double val = asDouble(context, args[0], true);
        double rnd = asDouble(context, args[1], true);
        if (rnd == 0){
            return ExprDouble.ZERO;
        }
        if ((val < 0 && rnd > 0) || (val > 0 && rnd < 0)){
            return ExprError.NUM;
        }
        double m = val % rnd;
        m = Maths.round(m, 8);
        if (m == rnd){
            m = 0;
        }
        return new ExprDouble(val - m);
    }

    public boolean equalish(double d1, double d2) {
        return Math.abs(d1 - d2) < 0.0000000001;
    }
}
